﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Chinesys.DataModel;
using Chinesys.Entities;
using Chinesys.Domain.DataMapper;
using Chinesys.Domain.BizRules;
using Chinesys.Domain.InputValidations;

namespace Chinesys.Domain
{
    public static class UserAppInRoleDomain
    {
        public static UserAppInRoleEntity GetUserAppInRoleById(int id)
        {
            UserAppInRoleEntity userAppInRole;

            using (ChinesysEntities db = new ChinesysEntities())
            {
                userAppInRole = UserAppInRoleDataMapper.UserAppInRoleFromRowToEntity(db.UserAppInRoles.SingleOrDefault(x => x.Id == id));
            }

            return userAppInRole;
        }

        private static UserAppInRoleEntity Insert(UserAppInRoleEntity userAppInRole)
        {
            using (ChinesysEntities db = new ChinesysEntities())
            {
                UserAppInRole userRole = UserAppInRoleDataMapper.UserAppInRoleFromEntityToRow(userAppInRole);
                db.AddToUserAppInRoles(userRole);
                db.SaveChanges();

                userAppInRole.Id = userRole.Id;
            }

            return userAppInRole;
        }

        private static UserAppInRoleEntity Update(UserAppInRoleEntity userAppInRole)
        {
            using (ChinesysEntities db = new ChinesysEntities())
            {
                UserAppInRole userRole = db.UserAppInRoles.SingleOrDefault(x => x.Id == userAppInRole.Id);

                if (userRole == null)
                {
                    throw new BizRulesException("Error El Usuario Role No se encuentra registrado, no se puede generar la modificación.");
                }

                userRole.Description = userAppInRole.Description;
                userRole.RoleId = userAppInRole.RoleId;
                userRole.UserAppId = userAppInRole.UserAppId;

                db.SaveChanges();
            }

            return userAppInRole;
        }

        public static UserAppInRoleEntity Save(UserAppInRoleEntity userAppInRole)
        {
            UserAppInRoleInputValidation validator = new UserAppInRoleInputValidation(userAppInRole);

            if(!validator.IsValid)
                throw new InputValidationException("Hubo errores de validación", validator);

            UserAppInRoleBizRules.OnSave(userAppInRole);

            if (userAppInRole.CurrentState == RowState.New)
                userAppInRole = Insert(userAppInRole);

            if (userAppInRole.CurrentState == RowState.Modified)
                userAppInRole = Update(userAppInRole);

            return userAppInRole;
        }

    }
}
